/**
 * Created by TEANA on 2017/6/11.
 */

module.exports = function (ngModule) {
  ngModule.factory('contentFactory',
    function ($resource,
              $q,
              $log,
              $native,
              Config) {

      var resource = $resource(Config.api.content, {}, {
        query:{
          method:'get',
          headers:$native.packageHeaders(),
          params:{
            infoCode:'@infoCode'
          },
          timeout:Config.timeout
        }
      });

      // 将stocks数组转换为字符串
      var formatStocks = function (data) {
        if(data.stocks){
          var array = [];
          for(var i = 0; i < data.stocks.length; i ++){
            array[i] = data.stocks[i].code;
          }
          var stockList = array.join(',');
          data.stockList = stockList;
        }else{
          data.stockList = '';
        }
        return data;
      };

      return {
        get:function (infoCode) {
          var defer = $q.defer();                 //声明延后执行
          resource.query({
            infoCode:infoCode
          }, function (response) {
            var data = response.info;
            data = formatStocks(data);
            defer.resolve(data);                //声明执行成功
          }, function (error) {
            defer.reject(error);                //声明执行失败
          });
          return defer.promise;                   //返回承诺，返回获取数据的API
        }
      };
    })
};
